package com.aaa.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码Servlet，负责生成并返回验证码图像。
 * @author Administrator
 * @webServlet("/api/getCaptchaImage")
 */
@WebServlet("/api/getCaptchaImage")
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * 处理GET请求，生成验证码图像并返回给客户端。
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @throws ServletException 如果发生Servlet相关异常
     * @throws IOException 如果发生I/O异常
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为JPEG图片
        // 设置响应头

        response.setContentType("image/jpeg");
        // 禁止缓存
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 生成随机验证码文本
        // 创建随机数生成器
        Random random = new Random();
        String captchaText = generateRandomString(random);

        // 将验证码文本保存到Session中
        // 将验证码存入session
        request.getSession().setAttribute("captcha", captchaText);

        // 创建验证码图像
        // 创建图像缓冲区
        int width = 100, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 绘制背景
        // 绘制背景
        g.setColor(new Color(204, 255, 255));
        g.fillRect(0, 0, width, height);

        // 绘制验证码文本
        // 绘制文字
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(captchaText, 10, 25);

        // 释放Graphics资源
        // 清理图形上下文
        g.dispose();

        // 将图像输出到响应流
        // 输出图像到客户端
        javax.imageio.ImageIO.write(image, "jpg", response.getOutputStream());
    }

    /**
     * 生成指定长度的随机字符串。
     * @param random 随机数生成器
     * @return 随机字符串
     */
    private String generateRandomString(Random random) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            // 根据随机数生成字符，并添加到字符串构建器
            sb.append(characters.charAt(random.nextInt(characters.length())));
        }
        return sb.toString();
    }
}
